
package com.ls.fw.mvc.struts.converter.sql;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.ls.fw.commons.core.log.PlatLogger;
import com.ls.fw.commons.core.utils.date.DateTypeUtil;
import com.ls.fw.mvc.struts.converter.DateTypeConverter;

/**
 * 
 * @author Defender
 * 2013-7-7 下午01:50:34
 */
public class DateConverter extends StrutsTypeConverter {
	
	
	private static final PlatLogger LOG = new PlatLogger(DateTypeConverter.class);
	 
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	 
    //暂时只考虑这几种日期格式
    public static final DateFormat[] ACCEPT_DATE_FORMATS = {
        new SimpleDateFormat(DEFAULT_DATE_FORMAT)
        ,new SimpleDateFormat("yyyy年MM月dd日")
        ,new SimpleDateFormat("yyyy/MM/dd")
        };
	/**
	 * String转换java.util.sql.date
	 *
	 */
	public Object convertFromString(Map arg0, String[] values, Class arg2) {
		if (values[0] == null || values[0].trim().equals("")) {
	            return null;
	      }
		if (values[0].contains(":")) {
            try {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(values[0]);
            } catch (ParseException e) {
                LOG.error("转换失败",e);
            }
        }else{
        	try {
                return new SimpleDateFormat("yyyy-MM-dd").parse(values[0]);
            } catch (ParseException e) {
                LOG.error("转换失败",e);
            }
        }
        for (DateFormat format : ACCEPT_DATE_FORMATS) {
            try {
                return new java.sql.Date(format.parse(values[0]).getTime());
            } catch (    ParseException | RuntimeException e) {
                continue;
            }
        }
        LOG.debug("can not format date string:" + values[0]);
        return null;
	}

	/**
	 * java.util.sql.date转换String 格式:yyyy-MM-dd hh:mm:ss
	 *
	 */
	public String convertToString(Map arg0, Object arg1) {
		try {
			return DateTypeUtil.toString(arg1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
}
